﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Threading;
using TimeBarPlugin.BarModel;
using Utils.Wpf;

namespace TimeBarPlugin
{
	internal class DailyChartGenerator : DispatcherObject
	{
		#region Attributes

		private double _width;
		private double _height;

		#endregion

		#region Properties

		public double ImageWidth
		{
			get
			{
				return _width;
			}
			set
			{
				if (Math.Abs(_width - value) > 0.01)
				{
					_width = value;
					_height = _width * 0.35;
				}
			}
		}

		#endregion

		#region Public Methods

		public FrameworkElement GenerateChart(IEnumerable<Bar> bars, DateTime day, decimal tick)
		{
			if (base.Dispatcher.CheckAccess())
			{
				DailyChart dailyChart = new DailyChart();

				dailyChart.Width = _width;
				dailyChart.Height = _height;

				dailyChart.Initialize(bars, day, tick);

				ControlRendererContainer controlRendererContainer = new ControlRendererContainer();
				controlRendererContainer.Content = dailyChart;
				controlRendererContainer.PrepareForRender();
				controlRendererContainer.Content = null;

				ControlRenderer controlRenderer = new ControlRenderer(96, 96);
				Image result = new Image() { Source = controlRenderer.Render(dailyChart), Stretch = Stretch.None };
				RenderOptions.SetBitmapScalingMode(result, BitmapScalingMode.NearestNeighbor);
				
				return result;
			}
			else
			{
				return (FrameworkElement)base.Dispatcher.Invoke(new Func<IEnumerable<Bar>, DateTime, decimal, UIElement>(this.GenerateChart), new object[] { bars, day, tick });
			}
		}

		#endregion
	}
}
